﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Domain;
using App.Web.ViewModels;
using App.Web.Utility;
using AutoMapper;
using System.IO;
using System.Drawing;
using App.Core.Extensions;
//using App.Core.Authentication;

namespace App.Web.Areas.Private.Controllers
{
    [Authorize(Roles = "Company Admin,Company User")]
    public class CompanyLogoController : BaseController
    {
		private AppEntities _Context = new AppEntities();

        #region Constructor
        public CompanyLogoController()
		{
		}

		public CompanyLogoController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
        #endregion Constructor

        #region Action Methods
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult List(int ID = 0)
        {
            Company company = _Context.Companies.FirstOrDefault(P => P.ID == ID);
            CompanyViewModel companyViewModel = Mapper.Map<Company, CompanyViewModel>(company);
            return View(companyViewModel);
        }

        /// <summary>
        /// This Action Method is used to upload the Image
        /// </summary>
        /// <param name="companyLogo"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult List(HttpPostedFileBase companyLogo, int companyID)// = 0, int companyLogoID = 0)
        {   
            Company company = _Context.Companies.FirstOrDefault(P => P.ID == companyID);
            CompanyViewModel companyViewModel = ViewBag.Company =  Mapper.Map<Company, CompanyViewModel>(company);
            ViewBag.CompanyID = companyID;

            if (companyID != base.LoggedInUser.Company.ID)
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Invalid Request.";
            else if(companyLogo == null)
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Please select an Image for your company.";
            else if(!WebUtil.IsValidImageFile(companyLogo))
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Sorry! Your selected file is not a valid Image.";
            //else if (images.Count == ConfigReader.MaxNumberLogo)
            //    ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = 
            //        String.Format("Sorry! You are not allowed to upload more than {0} Logo.",
            //        ConfigReader.MaxNumberLogo);
            else
            {                
                int w, h;
                String fileName = ImageManager.SaveTempJpeg(companyLogo.InputStream, ConfigReader.CompanyLogoAspectRatio, out w, out h);                
                ViewBag.WidthHeight = String.Format("{0},{1}", w, h);
                ViewBag.CropBoxImageUrl = ImageManager.GetTempImageUrl(fileName);                
                ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME] = companyLogo.FileName;
            }
            return View(companyViewModel);
        }

        [HttpPost]
        public ActionResult CropAndSaveImage(CompanyViewModel image)
        {
            cropAndSaveImage(image);
            return Json(image);
        }

        [HttpPost]
        public ActionResult DeleteCompanyLogo(int companyID)
        {            
            if (LoggedInUser.Company.ID != companyID)
                return Json(false);

            var company = _Context.Companies.FirstOrDefault(P => P.ID == companyID);
            if (company == null)
                return Json(false);
            else
            {
                ImageManager.DeleteCompanyLogo(company.LogoFile, companyID);                
                company.LogoFile = null;
                _Context.SaveChanges();
                
                return Json(true);
            }
        }
        #endregion Action Methods

        #region Helper Methods       

        private void cropAndSaveImage(CompanyViewModel viewModel)
        {            
            if (base.LoggedInUser.Company.ID == viewModel.ID)
            {                
                Company company = _Context.Companies.FirstOrDefault(P => P.ID == viewModel.ID);
                if (company != null && !viewModel.LogoFile.IsNullOrEmpty())
                {
                    String sourceImage = Server.MapPath(viewModel.LogoFile);
                    if (System.IO.File.Exists(sourceImage))
                    {
                        //Delete Existing Logo from file System, if any
                        if (!company.LogoFile.IsNullOrEmpty())
                        {
                            String existingLogo = Server.MapPath(ImageManager.GetCompanyLogoUrl(company.LogoFile, company.ID));
                            if (System.IO.File.Exists(existingLogo))
                                System.IO.File.Delete(existingLogo);
                        }
                        String[] coords = viewModel.CropProperty.Split(',');
                        viewModel.Width = (int)coords[2].ToFloat();
                        viewModel.Height = (int)coords[3].ToFloat();
                        Rectangle rectangle = new Rectangle(coords[0].ToInt(), coords[1].ToInt(), viewModel.Width, viewModel.Height);

                        String proposedFileName = Server.MapPath(ImageManager.GetCompanyLogoUrl(viewModel.OriginalFileName, viewModel.ID));
                        proposedFileName = ImageManager.GetNextFileName(proposedFileName);
                        String[] fileNames = ImageManager.SaveThumbnail(sourceImage, proposedFileName, rectangle, company.ID, true, ImageFor.CompanyLogo);                        
                        company.LogoFile = Path.GetFileName(fileNames[1]);
                        ///Delete Original Source Image from the Logo Directory
                        ///Also we can keep this file for future edit but keeping the source will get unnecessary space in the
                        ///serve, if user doesn't really using it. If need to change then they have to upload a new Image.
                        if (System.IO.File.Exists(fileNames[0]))
                            System.IO.File.Delete(fileNames[0]);
                        viewModel.LogoFile = ImageManager.GetCompanyLogoUrl(company.LogoFile, company.ID);

                        _Context.SaveChanges();
                    }
                }
            }
        }
        #endregion Helper Methods
    }
}
